import axios from 'axios'
import { VueAxios } from './axios'
import Vue from 'vue'
import router from '@/router'
import {Message, MessageBox} from 'element-ui'

// 创建 axios 实例
const service = axios.create({
  // baseURL: '/dev-api', // api base_url
  baseURL: '/api', // api base_url
  // timeout: 10000 // 请求超时时间
})

// 异常捕获
const err = (error) => {
  return Promise.reject(error)
}

// 请求拦截
service.interceptors.request.use(config => {
  const token = localStorage.getItem('token')
   if (token) {
     config.headers['token'] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
   }
  // config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
  return config
}, err)

// 详情拦截
service.interceptors.response.use((response) => {
  return new Promise((resolve, reject) => {
    if(response.data.code == 200) {
      resolve(response.data)
    }else if(response.data.code == 401){
      localStorage.clear()
      window.location.reload()
    }else {
      Message({
        message: response.data.message,
        type: 'error',
        duration: 5 * 1000
      })
      reject(response)
    }
  })

}, err)

const installer = {
  vm: {},
  install (Vue) {
    Vue.use(VueAxios, service)
  }
}

export {
  installer as VueAxios,
  service as axios
}
